package com.acce.gxsc.common;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.sdk.utils.ToastUtils;
import com.acce.sdk.widget.AcceBar;

import java.text.MessageFormat;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 编辑文本界面
 * Created by huxley on 17/2/4.
 */
public class EditTextActivity extends AppCompatActivity {

    String content;
    String title;
    int    length;

    @Bind(R.id.et)
    EditText mEt;
    @Bind(R.id.tv)
    TextView mTv;
    @Bind(R.id.accebar)
    AcceBar  mAccebar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_text);
        ButterKnife.bind(this);

        init(getIntent());
    }

    public void init(Intent intent) {
        content = intent.getStringExtra("content");
        title = intent.getStringExtra("title");
        length = intent.getIntExtra("length", 0);

        mAccebar.setTitleText(MessageFormat.format("编辑{0}", title));
        mTv.setText(MessageFormat.format("请输入{0}", title));
        if (content != null) {
            mEt.setText(content);
            mEt.setSelection(content.length());
        }
        if (length > 0) {
            mEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});
        }
    }

    private void save() {
        String content = mEt.getText().toString();
        if (content.isEmpty()) {
            ToastUtils.show(MessageFormat.format("请输入{0}", this.title));
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("content", content);
        setResult(RESULT_OK, intent);
        finish();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_edit_text, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_save:
                save();
                break;
        }

        return super.onOptionsItemSelected(item);
    }
}
